﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;

namespace Atosenet
{
    public abstract class BaseCollection<T> : Collection<T>
    {
        #region 初始化

        public BaseCollection()
        { }

        #endregion


        #region 公开函数

        public T Find(Predicate<T> match)
        {
            if (match == null)
                return default(T);

            for (int i = 0; i < this.Count; i++)
            {
                if (match(this.Items[i]))
                {
                    return this.Items[i];
                }
            }
            return default(T);
        }

        public T[] FindAll(Predicate<T> match)
        {
            if (match == null)
                return new T[0];

            List<T> result = new List<T>();

            for (int i = 0; i < this.Count; i++)
            {
                if (match(this.Items[i]))
                {
                    result.Add(this.Items[i]);
                }
            }
            return result.ToArray();
        }

        public bool Exists(Predicate<T> match)
        {
            if (match == null)
                return false;

            for (int i = 0; i < this.Count; i++)
            {
                if (match(this.Items[i]))
                {
                    return true;
                }
            }
            return false;
        }

        public void ForEach(Action<T> action)
        {
            if (action == null)
                return;

            for (int i = 0; i < this.Count; i++)
            {
                action(this.Items[i]);
            }
        }

        public T[] ToArray()
        {
            List<T> links = new List<T>();
            links.AddRange(this.Items);
            return links.ToArray();
        }

        public bool TrueForAll(Predicate<T> match)
        {
            if (match == null)
                return false;

            for (int i = 0; i < this.Count; i++)
            {
                if (!match(this.Items[i]))
                    return false;
            }
            return true;
        }

        #endregion


        #region 核心函数

        protected override void InsertItem(int index, T item)
        {
            if (!this.Contains(item))
                base.InsertItem(index, item);
        }
        
        #endregion
    }
}
